import {
  list
} from '../../../api/ingredients'
import {
  _get
} from '../../../api/collection_record'
import recipeApi from '../../../api/recipe'
import factorApi from '../../../api/factor'
import {
  useToast
} from '../../../miniprogram_npm/miniprogram-vc-components/toast/useToast';
import {
  routeAndState,
  numSettingsType
} from '../../../dataSource'
import {
  candidate
} from '../../../api/performce'



Component({
  properties: {
    dataSource: {
      type: Object,
      value: {},
      observer(data) {

        if (data?.data?.recipeId) {
          this.recipeHandler(data.data)
        }
      }
    },
    _ingredientsList: {
      type: Array,
      value: [],
      observer(data) {
        this.setData({
          ingredientsList: data
        })
      }
    },
    _list: {
      type: Array,
      value: [],
      observer(data) {
        this.setData({
          list: data
        })
      }
    },
    _alias: {
      type: Object,
      value: {},
      observer(data) {
        this.setData({
          alias: data
        })
      }
    }
  },
  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    dropList: [],
    selectList: [],
    //factorList: [],
    show: false,
    alias: {},
    checkboxValue: [],
    values: [],
    name: '',
    ingredientsList: [],
    id: '',
    dataSource: {},
    numSettingsType,
    // factorSelect: [],
    recordId: null,
    confirmShow: false,
    confirmList: routeAndState,
    pages: getCurrentPages(),
    preData: {},
    status: null,
    enable: true,
    total: 0,
    refreshLoading: false,
    enabledScroll: true,
    root: getApp().globalData.root,
    _historyList: [],
    _performanceData: {
      x: null,
      y: null,
      z: null,
      tRongCorrectionValue: null
    },
    _originData: {},
    enableEdit: true,
    compositionShow: false
  },
  methods: {
    addPF() {
      const recipeCombination = this.data.values.map((it) => {
        if (it.number && it.number != '0') {
          return {
            number: it.number,
            ingredients: it
          }
        }
      }).filter(it => it)
      if (this.data.selectList.length < 1) {
        wx.showToast({
          title: '没有添加原料',
          icon: 'error'
        })
        return
      }
      const numberSettings = this.selectComponent("#vc-number")?.getDataSource();

      const number_data = numberSettings.map(it => {
        return {
          name: it.name,
          numSelectManageId: it.numSelectManageId,
          remark: it.remark,
          sortNumber: it.sortNumber,
          value: it.value
        }
      })
      const {
        name,
        //  factorSelect

      } = this.data;

      const data = {
        name,
        recipeCombination,
        productionNumberDatas: number_data,
        //  factorManageId: factorSelect[0]
      }
      recipeApi.recipeAdd(data, (e) => {
        wx.showToast({
          title: '完成',
          icon: 'success'
        })
      })
    },
    onClose() {
      this.setData({
        show: false
      })
    },
    onPickerShow() {
      this.setData({
        show: true
      })
    },
    onChange(event) {
      const data = event.detail;
      this.setData({
        checkboxValue: data
      })

    },
    onSelectConfirm() {
      this.onClose();
      const dropList = [...this.data.dropList];
      let selectList = [...this.data.selectList];
      let checkList = [...this.data.checkboxValue];
      const dl = dropList.filter(it => {
        return !checkList.includes(String(it.value))
      })
      const sl = [...selectList, ...dropList.filter(it => {
        return checkList.includes(String(it.value))
      }).map(it => {
        return {
          ...it,
          number: it.number || '0'
        }
      })]
      this.setData({
        dropList: dl,
        checkboxValue: [],
        selectList: sl
      })
    },
    onLockOn() {
      this.setData({
        enabledScroll: false
      })
    },
    onUnLockOn() {
      this.setData({
        enabledScroll: true
      })
    },
    showPicker() {
      //排序
      this.sortArray();
      this.onPickerShow();
    },
    sortArray() {
      const dropList = [...this.data.dropList];
      if (dropList.length < 1) return
      dropList.sort((a, b) => {
        return String(a.text)[0].localeCompare(String(b.text)[0], 'zh-CN', {
          numeric: true
        })
      })
      this.setData({
        dropList
      })
    },
    xyzChange(event) {
      const key = event.currentTarget.dataset.value;
      this.setData({
        [key]: event.detail
      })
    },
    onFactorClose() {
      this.setData({
        fatorShow: false
      })
    },
    onFactorShow() {
      this.setData({
        fatorShow: true
      })
    },
    onFactorConfirm(event) {
      const obj = event.detail;
      this.setData({
        factorData: obj
      })
      // this.onFactorClose()
    },
 
    /**
     * 查询原料表
     */
    fetchIngredientsList() {
      list({
        status: 'ANNOUNCED'
      }, (e) => {
        const alias = {};
        e.map(it => {
          alias[it.id] = it.name;
        })
        this.fetchRecipeById();
        this.setData({
          list: e.sort((a, b) => {
            return a.name.localeCompare(b.name)
          }),
          ingredientsList: e,
          alias
        })
      })
    },
    /**
     * 查询所有配方
     */
    getAllRecipe() {
      recipeApi.recipeList({}, res => {
        const list = res.map(it => {
          return {
            text: it?.ingredients?.name,
            id: it?.ingredients?.id,
            number: it?.number
          }
        })
        this.setData({
          recipeListAll: list
        })
      })
    },
    selectHandler(event) {
      let arr = [...this.data.values];
      arr[event.currentTarget.dataset.index]['id'] = event.detail;
      this.setData({
        values: arr
      })
    },
    add(id, number) {
      this.setData({
        values: [...this.data.values, {
          id: id || '',
          number: number || ''
        }]
      })
    },
    numberChange(event) {

      const id = event.currentTarget.dataset.id;
      const arr = [...this.data.ingredientsList];
      const selectList = [...this.data.selectList];

      arr.forEach(it => {
        if (it.id === id) {
          it.number = event.detail;
        }
      })
      selectList.forEach(it => {
        if (it.value === id) {
          it.number = event.detail
        }
      })

      const total = this.getTotal(selectList);
      this.setData({
        ingredientsList: arr,
        selectList,
        total
      })
    },
    fetchRecipeById(id) {
      wx.showLoading({
        title: '加载中'
      })
      setTimeout(() => {
        wx.hideLoading()
      }, 1000)
      recipeApi.recipeId(id || this.data.id, (res) => {
        this.setData({
          _historyList: [res],
          _originData: res
        })
        this.recipeHandler(res);
      })
    },
    recipeHandler(res) {

      const {
        name
      } = res;
      const list = [...this.data.list];
      const values = res.recipeCombination?.map(it => {
        return {
          id: it?.ingredients?.id,
          number: it?.number
        }
      })
      const total = this.getTotal(values);
      const ingredientsList = this.data.ingredientsList.map(it => {
        return {
          ...it,
          number: values.find(item => {
            return item.id === it.id
          })?.number || '0'
        }
      })
      const alias = {};
      const d = res.recipeCombination.map(it => {
        alias[it?.ingredients?.id] = it?.ingredients.name;
        return {
          text: it?.ingredients.name,
          value: it?.ingredients.id,
          number: it?.number
        }
      })
      const dropList = ingredientsList.map(it => {
        const valid = d.every(item => item.value !== it?.id);
        if (valid) {
          return {
            text: it?.name,
            value: it?.id,
            number: ''
          }
        }
        return false
      }).filter(it => it)
      this.setData({
        values,
        name,
        dataSource: res,
        // factorSelect: [factorManageId],
        list,
        selectList: d,
        alias,
        ingredientsList,
        dropList,
        status: res.status,
        total,
        enableEdit: res.status === undefined || res.status === 'TO_BE_ANNOUNCED' || (this.data.root && res.status === 'CHECK')
      })

    },
    toggle(event) {
      const {
        index
      } = event.currentTarget.dataset;
      const checkbox = this.selectComponent(`.checkboxes-${index}`);
      checkbox.toggle();
    },
    /**
     * @param {*} event 
     * @description 跳转到原料
     */
    toMaterial(event) {
      const id = event.currentTarget.dataset.value.value;
      wx.navigateTo({
        url: '../material/index?id=' + id,
      })
    },
    noop() {},
    /**
     * 刷新配方列表
     */
    async onRefreshRecipe() {
      this.setData({
        refreshLoading: true
      })
      await this.fetchIngredientsList();
      const selectList = [...this.data.selectList],
        dropList = [...this.data.dropList],
        list = dropList.filter(it => {
          return selectList.find(item => {
            return item.value === it.value
          }) === undefined
        });
      this.setData({
        dropList: list,
        refreshLoading: false
      })

    },
    /**
     * @param {Array} list 
     * @return Number
     */
    getTotal(list) {
      const total = list.reduce((preVal, currentVal) => {
        return preVal + Number(currentVal.number)
      }, 0).toFixed(2);
      return total;
    },
    /**
     * 删除item
     * @param {*} event 
     */
    delectItem(event) {
      const index = event.currentTarget.dataset.index;
      const dropList = [...this.data.dropList],
        checkboxValue = [...this.data.checkboxValue],
        selectList = [...this.data.selectList];
      selectList[index].number = '0';
      checkboxValue.unshift(selectList[index].value);
      dropList.unshift(selectList[index]);
      selectList.splice(index, 1);
      const total = this.getTotal(selectList);
      this.setData({
        dropList,
        selectList,
        total,
        checkboxValue
      })
    },
    //判断资料里是否存在0
    validRecipeCombinationHasZero(arr) {
      return arr.some(it => {
        return it.number && String(it.number) == "0"
      })
    },
    /**
     * 更新 或发布
     */
    update() {
      const {
        name
      } = this.data;

      const recipeCombination = this.data.ingredientsList.filter(it => {
        return this.data.selectList.find(item => {
          return item.value === it.id
        }) !== undefined
      }).map(it => {
        return {
          ingredients: it,
          number: this.data.selectList.find(item => {
            return item.value === it.id
          })?.number
        }
      })
      if (this.validRecipeCombinationHasZero(recipeCombination)) {
        wx.showModal({
          showCancel: false,
          content: "份额不可以为0"
        })
        return
      }
      //  const new_or_old = this.data.factorData.calciumOxide ? this.data.factorData : this.data.factorDataSource;

      // const recipeOperationData = this.data.dataSource?.recipeOperationData?.map(it => {
      //   return {
      //     ...it,
      //     ...new_or_old[it['elementType']]
      //   }
      // })
      // // 查看是否有膨胀因子
      // const correctionAmount = recipeOperationData.find(it => {
      //   return it.elementType === 'correctionAmount'
      // })
      // if (correctionAmount === undefined) {
      //   recipeOperationData.push({
      //     elementType: 'correctionAmount',
      //     expansionFactor: this.data.factorData['correctionAmount']['expansionFactor']
      //   })
      // }
      const numberSettings = this.selectComponent("#vc-number")?.getDataSource();

      const number_data = numberSettings.map(it => {
        return {
          name: it.name,
          numSelectManageId: it.numSelectManageId,
          remark: it.remark,
          sortNumber: it.sortNumber,
          value: it.value
        }
      })
      const data = {
        name,
        recipeCombination,
        productionNumberDatas: number_data,
        ...this.data._performanceData
      }
      let _d = Object.assign({}, this.data.dataSource, data);
      if (this.data.status === 'CHECK' && this.data.root) {
        _d.status = "ANNOUNCED";
      }
      recipeApi.recipeUpdate(_d, () => {
        // selectItem = d;
        wx.showModal({
          title: '提示',
          content: '已完成保存，是否返回上一层?',
          success: (res) => {
            res.confirm && this.goBack(this.data.dataSource);
          }
        })
        if (_d.status === 'CHECK') {
          this.fetchRecipeById();
        }
      })
    },
    onDelectItems(event) {
      this.triggerEvent('delect', event.detail)
    },
    /**
     * 创建配方副本
     */
    create() {
      const {
        name,
        //factorSelect
      } = this.data;

      const recipeCombination = this.data.ingredientsList.filter(it => {
        return this.data.selectList.find(item => {
          return item.value === it.id
        }) !== undefined
      }).map(it => {
        return {
          ingredients: it,
          number: this.data.selectList.find(item => {
            return item.value === it.id
          })?.number
        }
      })
      if (this.validRecipeCombinationHasZero(recipeCombination)) {
        wx.showModal({
          showCancel: false,
          content: "份额不可以为0"
        })
        return
      }

      const newName = name + '-副本';
      wx.showModal({
        title: '填写配方副本名称',
        content: newName,
        editable: true,
        placeholderText: newName,
        success: async (res) => {
          if (res.confirm) {
            const numberSettings = this.selectComponent("#vc-number")?.getDataSource();

            const number_data = numberSettings.map(it => {
              return {
                name: it.name,
                numSelectManageId: it.numSelectManageId,
                remark: it.remark,
                sortNumber: it.sortNumber,
                value: it.value
              }
            })
            const data = {
              name: res.content || newName,
              recipeCombination,
              productionNumberDatas: number_data,
              ...this.data._performanceData,
              //    factorManageId: factorSelect[0],
              status: 'TO_BE_ANNOUNCED'
            }
            this.setData({
              preData: data
            })
            // if (this.data.recordId) {
            //   //如果没有釉料环节，那也就不必确认之前的步骤了
            //   const hasGlaze = await isDone(this.data.recordId, 'glazeId');
            //   if (!hasGlaze) {
            //     this.editHandler();
            //     return
            //   }
            //   const c = await this.asyncValid();
            //   if (!c) {
            //     this.onConfirmShow();
            //     return
            //   }
            // }
            this.editHandler();
          }
        }
      })
    },
    async asyncValid() {
      return new Promise((resolve, reject) => {
        _get(this.data.recordId, (res) => {
          const data = this.data.confirmList.map(it => {
            return {
              ...it,
              state: res[it['key']] !== null && res[it['key']] > 0
            }
          })
          this.setData({
            confirmList: data
          })
          //只要有一个流程无保存状态，弹框验证就不通过
          const validResult = data.every(it => it.state === false);
          resolve(validResult);
        }, reject)
      })
    },
    editHandler() {
      const _this = this,
        _data = this.data.preData;
      recipeApi.recipeAdd(_data, (e) => {
        selectItem = e;
        wx.showModal({
          title: '提示',
          content: '已完成保存，是否返回上一层?',
          success: (res) => {
            // res.confirm && _this.goBack(e);
            _this.goBack(e)
          }
        })
      })
    },
    onConfirmHide(valid) {
      this.setData({
        confirmShow: false
      })
      if (valid.detail) {
        this.editHandler();
      }
    },
    onConfirmShow() {
      this.setData({
        confirmShow: true
      })
    },
    goBack() {
      wx.navigateBack({
        delta: 1
      })
    },
    setDisbale(id) {

      _get(id, res => {

        this.setData({
          enable: res.status === 0
        })
      })
    },
    /**
     * 设置配方列表下拉框
     */
    fetchFactorList() {
      factorApi.getFactor({}, res => {
        const list = res.map(it => {
          return {
            name: it.name,
            value: it.id
          }
        })
        this.setData({
          factorList: list
        })
      })
    },
    onRecipeChange(event) {
      const _historyList = this.data._historyList;
      if (_historyList.find(k => k.id === event.detail.id) === undefined) {
        _historyList.push(event.detail);
      }
      this.recipeHandler(event.detail);
      this.setData({
        _historyList
      })
    },
    onNavChange(event) {
      this.recipeHandler(event.detail);
    },
    onPerformanceInputChange(event) {
      const {
        name,
        value
      } = event.detail;
      const _performanceData = this.data._performanceData;
      _performanceData[name] = value;
      this.setData({
        _performanceData
      })
    },
    useThis() {
      const _dataSource = JSON.parse(JSON.stringify(this.properties.dataSource));
      wx.showModal({
        title: "提示",
        content: `确定要应用此数据吗？`,
        success: res => {
          if (res.confirm) {
             candidate(_dataSource, ()=>{
               wx.showToast({
                 title: '原配方数据已替换，请手动保存修改',
                 icon: 'none'
               })
               this.triggerEvent('refresh',{
                 ..._dataSource,
                 id: _dataSource.recipeId
               });
             })
          }
        }
      })

    },
    toggleCompositionPopup() {
      this.setData({
        compositionShow: !this.data.compositionShow
      })
    },
    onAdd(event) {
 
      this.triggerEvent('add', event.detail)
    }
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  lifetimes: {
    attached() {
     
    }
  }
})